import networkx as nx
import matplotlib.pyplot as plt


# 读取数据并创建有向图
def load_graph(file_path):
    graph = nx.DiGraph()
    with open(file_path) as file:
      for line in file:
        if line.startswith("#"):
          continue
        source, target = map(int, line.strip().split())
        graph.add_edge(source, target)
    return graph


# 计算PageRank
def compute_pagerank(graph, alpha=0.85, max_iter=100, tol=1.0e-6):
    return nx.pagerank(graph, alpha=alpha, max_iter=max_iter, tol=tol)


# 可视化PageRank
def plot_pagerank(graph, pagerank_scores):
    plt.figure(figsize=(12, 12))
    pos = nx.spring_layout(graph)

    # 根据PageRank值调整节点的大小
    node_size = [v * 10000 for v in pagerank_scores.values()]

    nx.draw_networkx_nodes(graph, pos, node_size=node_size, node_color='blue', alpha=0.6)
    nx.draw_networkx_edges(graph, pos, arrows=True, alpha=0.3)
    plt.title("PageRank")
    plt.show()


if __name__ == '__main__':
    # 下载数据文件路径，请确保已下载数据到指定路径
    file_path = 'wiki-Vote.txt'
    graph = load_graph(file_path)
    pagerank_scores = compute_pagerank(graph)
    plot_pagerank(graph, pagerank_scores)